<template>
  <div ref="chartEl" class="chart-container"></div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch } from 'vue';
import * as echarts from 'echarts';

// 确保定义props类型
interface ChartData {
  time: string;
  value: number;
}

const props = defineProps<{
  chartData: ChartData[];
}>();

const chartEl = ref<HTMLElement | null>(null);
let chart: echarts.ECharts | null = null;

onMounted(() => {
  if (chartEl.value) {
    chart = echarts.init(chartEl.value);
    updateChart();

    // 添加窗口resize监听
    window.addEventListener('resize', handleResize);
  }
});

onUnmounted(() => {
  // 移除窗口resize监听
  window.removeEventListener('resize', handleResize);
  // 销毁图表实例
  chart?.dispose();
  chart = null;
});

watch(() => props.chartData, updateChart);

function handleResize() {
  chart?.resize();
}

function updateChart() {
  const option = {
    // 配置图表属性
    title: {
      text: '实时能源趋势',
      left: 'center',
      textStyle: {
        color: '#333',
        fontSize: 16,
      },
    },
    tooltip: {
      trigger: 'axis',
      formatter: (params: any) => {
        return `时间: ${params[0].name}<br>值: ${params[0].value}`;
      },
    },
    xAxis: {
      type: 'category',
      data: props.chartData.map((item) => item.time),
      axisLabel: {
        color: '#666',
        rotate: 30, // 文字倾斜
      },
      axisLine: {
        lineStyle: {
          color: '#ccc',
        },
      },
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        color: '#666',
      },
      splitLine: {
        lineStyle: {
          color: '#eee',
        },
      },
    },
    series: [{
      name: '能源趋势',
      type: 'line',
      data: props.chartData.map((item) => item.value),
      showSymbol: false,
      itemStyle: {
        color: '#36a2eb',
        borderColor: '#36a2eb',
        borderWidth: 2,
      },
      smooth: true,
      lineStyle: {
        color: '#36a2eb',
        width: 2,
      },
    }],
    grid: {
      left: '3%',
      right: '3%',
      bottom: '10%',
      top: '20%',
      containLabel: true,
    },
  };
  chart?.setOption(option);
}
</script>

<style scoped>
.chart-container {
  width: 100%;
  height: 100%;
  min-height: 300px;
}
</style>